/*
Автор: HungryMelon, aka Mel0n1sMel0n
https://youtu.be/qgSkRPb6udU
//
Программа написана для демонстрации библиотеки RS-232 by Teuniz
https://gitlab.com/Teuniz/RS-232
*/

#include "stdio.h"
#include "stdlib.h"
#include "rs232.c"
#include "unistd.h"
#include "util.c"

int main(void){
	
	//settings
	int port_num = RS232_GetPortnr("ttyUSB0");
	int baudrate = 9600; 
	char mode[]={'8','N','1',0}; 
	//
	uint8_t buf[9];
	uint8_t ready_byte[] = {'1', '0', '0', '0', '0', 0, 0, 0, 0};
	int n, isReady = 0;

	if(RS232_OpenComport(port_num, baudrate, mode, 0)){
		printf("Can't open port by %s", comports[port_num-1]);
		return 1;
	}
	while(1){
		usleep(100000);
		int n = RS232_PollComport(port_num, buf, 9);
		if(!isReady){
			if (n > 0){
				buf[n] = 0;
				for(int i = 0; i < n; i++) if(buf[i] < 32) buf[i] = 0;
			}
			if(check_equ(ready_byte, buf)) isReady = 1;
		} else if(isReady){
			//send request
			uint8_t *inp;
			inp = input("> ");
			
			RS232_cputs(port_num, inp);
			
			usleep(100000);
			int n = RS232_PollComport(port_num, buf, 9);
			if (n > 0){
				buf[n] = 0;
				for(int i = 0; i < n; i++) if(buf[i] < 32) buf[i] = 0;
			}
			printf("%s \t %s\n", (char *)inp, (char*)buf);
			free(inp);
		}
	}
	RS232_CloseComport(port_num);
	return 0;
}